#!/usr/bin/php

<?php

require("../barDB.php");

//
// Temperature monitor shell script for DS18b20 based I2C probes
//
// Device data should look like this:
//
// @raspberrypi ~ $ cat /sys/bus/w1/devices/28-DEVICE/w1_slave
// 9c 01 4b 46 7f ff 04 10 7a : crc=7a YES
// 9c 01 4b 46 7f ff 04 10 7a t=25750
//

// path to the sys device
$BASE_PATH = "/sys/bus/w1/devices";

// device string name of the ambient temperature sensor
$AMBIENT_ID = "28-0000054e3702";

// device string name of the refrigerator temperature sensor
$COOLER_ID = "28-0000054ef657";

// Internal - dont touch below
$TEMPERATURE_FILE = "w1_slave";

$USE_DEGREES_F = true;

function GetTemperature( $fullPath, $useDegreesF )
{
    $temperatureReading = -1.0;

    if( file_exists( $fullPath ) )
    {
        $handle = fopen( $fullPath, "r" );

        $data = fread( $handle, max( filesize( $fullPath ), 512 ) );

        $strings = explode( "t=", $data );

        $temperature = intval( trim( end( $strings ) ) );

        if( is_int( $temperature ) )
        {
            $temperature /= 1000.0;

            if( $useDegreesF == true )
            {
                $temperatureReading = $temperature * 9.0 / 5.0 + 32.0;
            }
        }

        fclose( $handle );
    }

    return $temperatureReading;
}

function AddCoolerTemperature( $temperature )
{
    $db = new BeerDB( );

    $now = time();

    $db->AddTemperature( $temperature, $now );

    $db->close();
}

$dir = dirname( __FILE__ );
chdir( $dir . '/..' );
if( $dirHandle = opendir( $BASE_PATH ) )
{
    while( $entry = readdir( $dirHandle ) )
    {
        if( ( $entry == $AMBIENT_ID ) ||
            ( $entry == $COOLER_ID ) )
        {
            $reading = GetTemperature( $BASE_PATH . '/' . $entry . '/' . $TEMPERATURE_FILE, $USE_DEGREES_F );

            print "Entry: $entry = $reading\n";

            if( $entry == $COOLER_ID )
            {
                AddCoolerTemperature( $reading );
            }
        }
    }
}

